#后端代码和PLC、服务器通信
import asyncio
import socket
import websockets



#WS客户端
async def main_ws():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello from client")
        print("> Hello from client")
        async for message in websocket:
            print(f"Received: {message}")
    #关闭WS链接
    websocket.close()

#TCP客户端
async def main_tcp():
    # 创建socket对象
    socket_client = socket.socket()
    # 连接到服务器（即PLC）
    socket_client.connect(("localhost", 8888))
    #不断地接受消息发送消息
    while True:
        send_msg = input("请输入要发送给服务端的消息：")
        if send_msg == "exit":
            break
        # 发送消息
        socket_client.send(send_msg.encode("UTF-8"))
        # 接受消息
        recv_data = socket_client.recv(1024).decode("UTF-8")    # 1024是缓冲区大小，一般就填1024， recv是阻塞式
        print(f"服务端回复的消息是：{recv_data}")
    # 关闭连接
    socket_client.close()


if __name__ == "__main__":
    asyncio.run(main_ws())
    asyncio.run(main_tcp())